import re

from django.contrib.auth.backends import ModelBackend

from users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    return {
        'token': token,
        'user_id': user.id,
        'username': user.username
    }

class UsernameMobileAuthBackend(ModelBackend):

    #重写django原有的验证方法，并且判断用户名是否是手机号，如果是手机号必须和注册的手机号相等

    def authenticate(self, request, username=None, password=None, **kwargs):
    # def authenticate(username,password=None,):
        if re.match('^1[3-9]\d{9}$', username):
            user = User.objects.get(mobile=username)

        else:
            user = User.objects.get(username=username)

        #验证密码

        if user is not None and user.check_password(password):
            return user

